const http = require('http');
const url = require('url');
const fs = require('fs');
const mime = require('mime');
const path = require('path');
const querystring = require('querystring');
let users = [];
const handleRequest = (req, res) => {
  const {
    pathname,
    query
  } = url.parse(req.url, true);
  if (pathname === '/') {
    res.end('homepage');
  } else if (pathname === '/users') {
    switch (req.method) {
      case 'GET':
        if (query.id) {
          let user = users.find(user => user.id === Number(query.id));
          res.end(JSON.stringify(user));
        } else {
          //res.statusCode = 500;
          //res.end();
          res.end(JSON.stringify(users));
        }
        break;
      case 'POST':
        getRequestBody(req).then(user => {
          //客户端新增加用户的不携带ID，而是由服务器端产品
          //最后一个用户的ID+1
          user.id = users.length>0?users[users.length-1].id+1:1;
          users.push(user);
          res.statusCode = 201;
          res.end(JSON.stringify(users));
        });
        break;
      case 'DELETE':
        users = users.filter(user => user.id !== Number(query.id));
        res.end(JSON.stringify(users));
        break;
      case 'PUT':
        getRequestBody(req).then(updateUser => {
          users = users.map(user => {
            if (user.id === Number(query.id)) {
              return { ...user,
                ...updateUser
              };
            } else {
              return user;
            }
          });
          res.end(JSON.stringify(users));
        });
        break;
      default:
        break;
    }
  } else {
    let filePath = path.join(__dirname, 'static', pathname);
    if (fs.existsSync(filePath)) {
      const fileContent = fs.readFileSync(filePath);
      res.statusCode = 200;
      res.end(fileContent);
      return;
      const newETag = fileContent.length;
      const oldEtag = req.headers['if-none-match'];;
      if (newETag == oldEtag) {
        res.statusCode = 304;
        return res.end();
      } else {
        const fileType = mime.getType(filePath);
        res.setHeader('Content-Type', fileType);
         if(filePath.endsWith('.html')){
          res.setHeader('Cache-Control', 'max-age=0');
        }else{
          res.setHeader('Cache-Control', 'max-age=10');
        }
        res.setHeader('Etag', fileContent.length);
        res.statusCode = 200;
        res.end(fileContent);
      }
    } else {
      res.statusCode = 404;
      res.end('Not Found');
    }
  }
};
function getRequestBody(req) {
  return new Promise(resolve => {
    let buffers = [];
    req.on('data', data => {
      buffers.push(data);
    });
    req.on('end', () => {
      const concatBuffer = Buffer.concat(buffers);
      let body = concatBuffer.toString();
      const contentType = req.headers['content-type'] || 'application/json';
      if (contentType === 'application/x-www-form-urlencoded') {
        resolve(querystring.parse(body));
      } else if (contentType === 'application/json') {
        resolve(JSON.parse(body));
      } else {
        resolve(body);
      }
    });
  });
}
const server = http.createServer(handleRequest);
server.listen(8080, () => console.log('server is started on port 8080'));